const express = require('express');
const cors = require('cors');

const path = require('path')
console.log(path.join(__dirname));//C:\Users\86136\Desktop\全栈历练练习\7.30


const moment = require('moment')
const fs = require('fs')


const artTemplate = require('art-template');
const express_template = require('express-art-template');
const session = require('express-session')

//挂载路由中间件
const router = require('./router/router.js')
const frontRouter = require('./router/frontRouter.js')

const app = express();


//初始化数据
app.use(session({
    name: 'SESSIONID',  // session会话名称存储在cookie中的键名
    secret: '%#%￥#……%￥', // 必填项，用户session会话加密（防止用户篡改cookie）
    cookie: {  //设置session在cookie中的其他选项配置
        path: '/',
        secure: false,  //默认为false, true 只针对于域名https协议
        maxAge: 60000 * 24,  //设置有效期为24分钟，说明：24分钟内，不访问就会过期，如果24分钟内访问了。则有效期重新初始化为24分钟。
    }
}))


//设置托管静态资源中间件
app.use('/uploads', express.static(__dirname + '/uploads'));
app.use('/static', express.static(__dirname + '/static'));

// const { CLIENT_RENEG_WINDOW } = require('tls');


app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

//配置模板的路径
app.set('views', __dirname + '/views/');
//设置express_template模板后缀为.html的文件(不设这句话，模板文件的后缀默认是.art)
app.engine('html', express_template);
//设置视图引擎为上面的html
app.set('view engine', 'html');
//允许跨域
app.use(function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*")
    next();
})

//定义一个过滤器dateFormat
artTemplate.defaults.imports.dateFormat = function (time, format = 'YYYY-MM-DD HH:mm:ss') {
    return moment.unix(time).format(format);
}

artTemplate.defaults.imports.dealDate = function (date, format = 'YYYY-MM-DD HH:mm:ss') {
    return moment(date).format(format);
}



//前台apijiekou
app.use('/api', frontRouter)



// 中间件统一校验session权限
app.use((req, res, next) => {
    //有些路由需要放行 不需要校验 如login logout dologin
    let path = req.path.toLowerCase();
    let unPermission = ['/login', '/logout', '/dologin', '/ajaxlogin', '/register', '/ajaxregister', '/ajaxemail', '/editLogo']
    if (!unPermission.includes(path)) {
        //不再放行内则需要校验
        console.log(req.path, '-session校验')
        console.log(req.session.userInfo, '-session校验')
        if (req.session.userInfo) {
            //权限正确
            next();
        } else {
            //权限失败
            res.redirect('/login');
            return;
        }
    } else {
        //放行
        next();
    }
})


app.use(router)

app.listen(8800, () => {
    console.log('明德8888')
})